package hu;

import java.util.*;

public class Main1 {
    static class  Node{
        int x, y, z;

        public Node(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int t = sc.nextInt();
        int[][] nums = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                nums[i][j] = sc.nextInt();
            }
        }
        int[][][] dp = new int[n][m][4];
        for(int[][] a : dp){
            for(int[] b : a){
                Arrays.fill(b, Integer.MAX_VALUE / 2);
            }
        }
        dp[0][0][0] = 0;
        int[] dx = {-1,0,1,0}, dy ={0,-1,0,1};
        Queue<Node> q = new LinkedList<>();
        q.offer(new Node(0,0,0));
        while(!q.isEmpty()){
            Node a = q.poll();
            int dis = dp[a.x][a.y][a.z];
            if(a.x == n - 1 && a.y == m- 1){
                System.out.println(dis);
                return;
            }
            for (int i = 0; i < 4; i++) {
                int x = a.x + dx[i], y = a.y + dy[i];
                if(x >= 0 && x < n && y >= 0 && y < m){
                    int z = a.z + (Math.abs(nums[x][y] - nums[a.x][a.y]) > t ? 1 : 0);
                    if(z <= 3 && dp[x][y][z] > dis + 1){
                        dp[x][y][z] = dis + 1;
                        q.offer(new Node(x,y,z));
                    }
                }
            }
        }
        System.out.println(-1);
    }
}
/*
4 4 10
10 20 30 40
100 120 140 160
200 230 260 290
300 400 500 600

1 10 1
11 12 200 14 15 16 317 18 19 20
 */